package com.yxq.mdt.app.modules.socialcontact.ui.fragment;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseFragment;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.personal.bean.EditPicutreResultBean;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.bean.UpdateAttributeRequestBean;
import com.yxq.mdt.app.modules.personal.model.UserModel;
import com.yxq.mdt.app.modules.personal.ui.activity.RechargeActivity;
import com.yxq.mdt.app.modules.picturebrowse.ui.PictureActivity;
import com.yxq.mdt.app.modules.socialcontact.adapter.SocialPhotoAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.GiftResultBean;
import com.yxq.mdt.app.modules.socialcontact.bean.GivePresentBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialPersonalHomepageBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialPersonalMyHomepageBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialPersonalHomePresenter;
import com.yxq.mdt.app.modules.socialcontact.presenter.mainSocialPersonalHomeContract;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.widgets.OssHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 相册
 */
public class SocialPhotoFragment extends BaseFragment<MainSocialPersonalHomePresenter> implements mainSocialPersonalHomeContract.View {
    public static final String EXTRA_TEXT = "extra_text";
    SocialPhotoAdapter socialPhotoAdapter;
    @BindView(R.id.social_photo_recyclerView)
    RecyclerView socialPhotoRecyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<SocialPersonalHomepageBean.PhotoImgFileBean> photoImgFileBeans;
    private String userId = "";
    MyPersonalBean myPersonalBean;
    List<String> imageList;
    List<LocalMedia> images;
    int len = 0;

    @Override
    protected int attachLayoutId() {
        setImmersionBarEnabled(false);
        return R.layout.fragment_social_photo;
    }

    @Override
    protected MainSocialPersonalHomePresenter getPresenter() {
        return new MainSocialPersonalHomePresenter(this, new MainSocialContactModel());
    }

    @Override
    public void initView(View view) {
        myPersonalBean = Hawk.get(SPKey.SP_KEY_USER_MY_INFO);
        Bundle bundle = getArguments();
        if (bundle != null) {
            userId = bundle.getString("userId");
        }
        photoImgFileBeans = new ArrayList<>();
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        socialPhotoRecyclerView.setLayoutManager(staggeredGridLayoutManager);
        socialPhotoAdapter = new SocialPhotoAdapter(getActivity(), userId.equals(myPersonalBean.getUserId() + ""), R.layout.item_layout_photo_list, photoImgFileBeans);
        socialPhotoRecyclerView.setAdapter(socialPhotoAdapter);
        socialPhotoAdapter.setEmptyView(R.layout.layout_empty_view, socialPhotoRecyclerView);
        socialPhotoAdapter.isUseEmpty(false);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
                    mPresenter.getGaUserExtVoById(userId);
                }
        );
        socialPhotoRecyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 20, false));
    }

    @Override
    public void initData() {
        imageList = new ArrayList<>();
        mPresenter.getGaUserExtVoById(userId);
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    //打开图片选择器
    private void selectImages() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(Integer.MAX_VALUE)//最大选择数目
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                //封面返回图片集
                case PictureConfig.CHOOSE_REQUEST:
                    //compressPath 压缩图片地址
                    // 图片选择结果回调
                    images = PictureSelector.obtainMultipleResult(data);
                    parseLocalMedia(images);
                    if (images != null && images.size() > 0) {
                        imageList.clear();
                        uploadPictures();
                    }
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + requestCode);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 上传封面至阿里云
     */
    @SuppressLint({"AutoDispose", "CheckResult"})
    private void uploadPictures() {
        Observable.fromIterable(images)
                .observeOn(Schedulers.io())
                .map(localMedia -> {
                    File file = new File(localMedia.getCompressPath());
                    OssHelper.getOss(mContext, true).putObject(OssHelper.getPutObjectRequest(OssHelper.GS_APP_VOICE + file.getName(), file.getPath()));
                    return OssHelper.getOssPrefixUrl(OssHelper.GS_APP_VOICE, file.getName());
                })
                .subscribe(s -> {
                    len++;
                    imageList.add(s);
                    if (len == images.size()) {
                        finishUploadImages(imageList);
                    }
                }, Throwable -> {
//                    Log.e("封面", "上传失败");
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            ToastUtils.showShort("上传失败请重新上传");
//                        }
//                    });
                });
    }

    /**
     * 上传本地图片完成
     *
     * @param images
     */
    private void finishUploadImages(List<String> images) {
        List<SocialPersonalHomepageBean.PhotoImgFileBean> uploadImageBeanList = socialPhotoAdapter.getData();

        int index = 0;
        for (SocialPersonalHomepageBean.PhotoImgFileBean uploadImageBean : uploadImageBeanList) {
            if (uploadImageBean.getId() == -2 && !uploadImageBean.getFilePath().startsWith("http")) {
                uploadImageBean.setFilePath(images.get(index));
                uploadImageBean.setId(index);
                index++;
            }
        }
        updateAttribute(socialPhotoAdapter.getData());
    }

    /**
     * 更新封面
     *
     * @param imageList 封面图片集合
     */
    private void updateAttribute(List<SocialPersonalHomepageBean.PhotoImgFileBean> imageList) {

        UpdateAttributeRequestBean updateAttributeRequestBean = new UpdateAttributeRequestBean();
        updateAttributeRequestBean.setTagType(5);//封面图
        updateAttributeRequestBean.setFileType(1);//图片
        List<UpdateAttributeRequestBean.FilePathBean> filePath = new ArrayList<>();
        for (SocialPersonalHomepageBean.PhotoImgFileBean uploadImageBean : imageList) {
            if (uploadImageBean.getId() != -2 && uploadImageBean.getId() != -1) {
                UpdateAttributeRequestBean.FilePathBean filePathBean = new UpdateAttributeRequestBean.FilePathBean();
                filePathBean.setFilePath(uploadImageBean.getFilePath());
//                filePathBean.setFileLength(StringUtils.getMediaDuration(uploadImageBean.getFilePath()));
                filePath.add(filePathBean);
            }
        }

        updateAttributeRequestBean.setFilePath(filePath);//图片集合
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(updateAttributeRequestBean));
        //更新相册
        UserModel.updateAttribute(body, new ApiModel.CommonCallback<EditPicutreResultBean>() {
            @Override
            public void onSuccess(EditPicutreResultBean editPicutreResultBean) {
                ToastUtils.showShort("成功");
            }

            @Override
            public void onError(String errMsg) {
                ToastUtils.showShort(errMsg);
            }
        });
    }

    /**
     * 封面图片
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {
        //uploadImageBean.setId(-2); 本地图片
        //uploadImageBean.setId(-1);上传图片图标
        List<SocialPersonalHomepageBean.PhotoImgFileBean> data = new ArrayList<>();
        SocialPersonalHomepageBean.PhotoImgFileBean uploadImageBean;
        for (LocalMedia localMedia : images) {
            uploadImageBean = new SocialPersonalHomepageBean.PhotoImgFileBean();
            uploadImageBean.setId(-2);
            uploadImageBean.setFilePath(localMedia.getCompressPath());
            data.add(uploadImageBean);
        }
        List<SocialPersonalHomepageBean.PhotoImgFileBean> temp = socialPhotoAdapter.getData();
//        temp.remove(temp.size() - 1);
        temp.addAll(data);
//        SocialPersonalHomepageBean.PhotoImgFileBean photoImgFileBean = new SocialPersonalHomepageBean.PhotoImgFileBean();
//        photoImgFileBean.setId(-1);
//        temp.add(photoImgFileBean);
        socialPhotoAdapter.setNewData(temp);
    }

    @Override
    public void onLoadMyGaUserExtVoByIdSuccess(SocialPersonalMyHomepageBean socialPersonalMyHomepageBean) {

    }

    @Override
    public void onLoadMyGaUserExtVoByIdFailed() {

    }

    @Override
    public void onLoadGaUserExtVoByIdSuccess(SocialPersonalHomepageBean socialPersonalHomepageBean) {
        refreshLayout.finishRefresh();
        if (userId.equals(myPersonalBean.getUserId() + "")) {
            //自己人 可以编辑相册
            List<SocialPersonalHomepageBean.PhotoImgFileBean> photoImgFileBeanList = new ArrayList<>();
            //添加一个假数据，上传按钮图标
            SocialPersonalHomepageBean.PhotoImgFileBean photoImgFileBean = new SocialPersonalHomepageBean.PhotoImgFileBean();
            photoImgFileBean.setId(-1);
            photoImgFileBeanList.add(photoImgFileBean);
            photoImgFileBeanList.addAll(socialPersonalHomepageBean.getPhotoImgFile());
            socialPhotoAdapter.setNewData(photoImgFileBeanList);
        } else {
            socialPhotoAdapter.setNewData(socialPersonalHomepageBean.getPhotoImgFile());
            socialPhotoAdapter.isUseEmpty(!(socialPhotoAdapter.getData().size() > 0));
        }
        socialPhotoAdapter.setOnItemChildClickListener((adapter, view1, position) -> {
            if (socialPhotoAdapter.getItem(position).getId() == -1) {
                //添加相册图片
                //选择图片
                selectImages();
                return;
            }
            switch (view1.getId()) {
                case R.id.panic_tv_photo_img:
                    //预览
                    Intent intent = new Intent(mContext, PictureActivity.class);
                    int id = socialPhotoAdapter.getItem(position).getId();
                    ArrayList<String> images = new ArrayList<>();
                    int index = 0;
                    int selectIndex = 0;
                    for (SocialPersonalHomepageBean.PhotoImgFileBean photoImgFile : socialPhotoAdapter.getData()) {
                        if (photoImgFile.getId() != -1 && (photoImgFile.getShowStatus() == 1 || userId.equals(myPersonalBean.getUserId() + ""))) {
                            images.add(photoImgFile.getFilePath());
                            if (id == photoImgFile.getId()) {
                                selectIndex = index;
                            }
                            index++;
                        }
                    }
                    intent.putExtra("position", selectIndex);
                    intent.putExtra("images", images);
                    mContext.startActivity(intent);
                    break;
                case R.id.item_iv_delete:
                    //删除
                    socialPhotoAdapter.remove(position);
                    updateAttribute(socialPhotoAdapter.getData());
                    break;
                case R.id.text:
                    CostumerDialog dialog = new CostumerDialog.Builder(getActivity(), R.style.custom_dialog_no_match)
                            .setContentView(R.layout.dialog_clear_cache_layout)
                            .setCancelable(true)
                            .create();

                    TextView title = dialog.findViewById(R.id.tv_title);

                    title.setText("打赏");

                    TextView content = dialog.findViewById(R.id.tv_content);
                    content.setText("打赏1蜜豆查看一张图片");

                    //充值
                    TextView sure = dialog.findViewById(R.id.tv_sure);
                    sure.setText("打赏TA一下");
                    sure.setOnClickListener(v -> {
                        //查看相册
                        MainSocialContactModel.setaddOrUpdateReward(socialPhotoAdapter.getItem(position).getId() + "", new ApiModel.CommonCallback<GiftResultBean>() {
                            @Override
                            public void onSuccess(GiftResultBean s) {
                                if (s != null && "500".equals(s.getStatus())) {
                                    openChang();
                                } else {
                                    showCenterToast("付费成功");
                                    socialPhotoAdapter.getData().get(position).setShowStatus(1);
                                    socialPhotoAdapter.notifyDataSetChanged();
                                }
                            }

                            @Override
                            public void onError(String errMsg) {
                                showCenterToast("付费失败");
                            }
                        });
                        dialog.dismiss();
                    });

                    //取消
                    TextView cancel = dialog.findViewById(R.id.tv_cancel);
                    cancel.setText("取消");
                    cancel.setOnClickListener(v -> {
                        dialog.dismiss();
                    });
                    dialog.show();
                    break;
                default:
            }
        });
    }

    @Override
    public void onLoadGaUserExtVoByIdFailed() {
        refreshLayout.finishRefresh();
    }

    @Override
    public void onLoadRelationSuccess(String s) {

    }

    @Override
    public void onLoadRelationFailed() {

    }

    @Override
    public void onLoadSelectByGsPresentPageListSuccess(GivePresentBean givePresentBean) {

    }

    @Override
    public void onLoadSelectByGsPresentPageListFailed() {

    }

    private void openChang() {
        CostumerDialog dialog = new CostumerDialog.Builder(getActivity(), R.style.custom_dialog_no_match)
                .setContentView(R.layout.dialog_clear_cache_layout)
                .setCancelable(true)
                .create();

        TextView title = dialog.findViewById(R.id.tv_title);

        title.setText("温馨提示");

        TextView content = dialog.findViewById(R.id.tv_content);
        content.setText("余额不足,充值才可以继续操作,是否需要充值?");

        //充值
        TextView sure = dialog.findViewById(R.id.tv_sure);
        sure.setText("充值");
        sure.setOnClickListener(v -> {
            Intent it = new Intent(getActivity(), RechargeActivity.class);
            getActivity().startActivity(it);
            dialog.dismiss();

        });

        //取消
        TextView cancel = dialog.findViewById(R.id.tv_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
        dialog.show();
    }
}
